-
Notifications
You must be signed in to change notification settings - Fork 31
Cors configuration for fhir api service #89
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
WalkthroughThis change centralizes CORS (Cross-Origin Resource Sharing) configuration by removing all Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant DynamicCorsFilter
participant JwtUserIdValidationFilter
participant CorsConfig
participant Controller
Client->>DynamicCorsFilter: HTTP Request (with Origin header)
DynamicCorsFilter->>DynamicCorsFilter: Check allowed origins
alt Origin allowed
DynamicCorsFilter->>Client: Set CORS headers
end
alt OPTIONS request
DynamicCorsFilter->>Client: Respond 200 OK (preflight)
else
DynamicCorsFilter->>JwtUserIdValidationFilter: Forward request
JwtUserIdValidationFilter->>JwtUserIdValidationFilter: Set CORS headers, validate JWT
JwtUserIdValidationFilter->>Controller: Forward request if valid
Controller->>Client: Response
end
Possibly related PRs
Suggested reviewers
Poem
✨ Finishing Touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 6
🧹 Nitpick comments (7)
src/main/java/com/wipro/fhir/controller/test/Test.java (1)
45-45: Removed redundant controller-level@CrossOriginannotation.
This aligns with the new global CORS setup; please remove the now-unusedCrossOriginimport to clean up the code.src/main/java/com/wipro/fhir/controller/healthIDvalidate/HealthIDValidateController.java (1)
27-27: Clean up unused import.The
@CrossOriginimport is no longer needed since all annotations have been removed as part of the CORS centralization.-import org.springframework.web.bind.annotation.CrossOrigin;src/main/java/com/wipro/fhir/controller/carecontext/CareContextController.java (1)
27-27: Clean up unused import.The
@CrossOriginimport is no longer needed since all annotations have been removed.-import org.springframework.web.bind.annotation.CrossOrigin;src/main/java/com/wipro/fhir/controller/healthID/CreateHealthIDWithMobileOTP.java (1)
28-28: Clean up unused import.The
@CrossOriginimport is no longer needed.-import org.springframework.web.bind.annotation.CrossOrigin;src/main/java/com/wipro/fhir/controller/generateresource/ResourceRequestGateway.java (1)
27-27: Clean up unused import.The
@CrossOriginimport is no longer needed.-import org.springframework.web.bind.annotation.CrossOrigin;src/main/java/com/wipro/fhir/controller/v3/abha/CreateAbhaV3Controller.java (1)
6-6: Remove unused import.The
@CrossOriginimport is no longer needed since the annotations have been removed.-import org.springframework.web.bind.annotation.CrossOrigin;src/main/java/com/wipro/fhir/controller/healthCard/GenerateHealthIDCardController.java (1)
27-27: Remove unused import.The
@CrossOriginimport is no longer needed since the annotations have been removed.-import org.springframework.web.bind.annotation.CrossOrigin;
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (21)
src/main/environment/common_ci.properties(1 hunks)src/main/environment/common_example.properties(1 hunks)src/main/java/com/wipro/fhir/config/CorsConfig.java(1 hunks)src/main/java/com/wipro/fhir/controller/carecontext/CareContextController.java(3 hunks)src/main/java/com/wipro/fhir/controller/eaushdhi/EAushadhiController.java(5 hunks)src/main/java/com/wipro/fhir/controller/facility/FacilityController.java(3 hunks)src/main/java/com/wipro/fhir/controller/generateresource/ResourceRequestGateway.java(4 hunks)src/main/java/com/wipro/fhir/controller/healthCard/GenerateHealthIDCardController.java(2 hunks)src/main/java/com/wipro/fhir/controller/healthID/CreateHealthIDWithBio.java(4 hunks)src/main/java/com/wipro/fhir/controller/healthID/CreateHealthIDWithMobileOTP.java(5 hunks)src/main/java/com/wipro/fhir/controller/healthID/CreateHealthIDWithUID.java(6 hunks)src/main/java/com/wipro/fhir/controller/healthID/CreateHealthIdRecord.java(3 hunks)src/main/java/com/wipro/fhir/controller/healthIDvalidate/HealthIDValidateController.java(3 hunks)src/main/java/com/wipro/fhir/controller/patientdatahandler/HigherHealthFacilityController.java(2 hunks)src/main/java/com/wipro/fhir/controller/patientdatahandler/PatientDataGatewayController.java(3 hunks)src/main/java/com/wipro/fhir/controller/test/Test.java(2 hunks)src/main/java/com/wipro/fhir/controller/v3/abha/CreateAbhaV3Controller.java(5 hunks)src/main/java/com/wipro/fhir/controller/v3/abha/LoginAbhaV3Controller.java(4 hunks)src/main/java/com/wipro/fhir/utils/DynamicCorsFilter.java(1 hunks)src/main/java/com/wipro/fhir/utils/FilterConfig.java(1 hunks)src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java(4 hunks)
🧰 Additional context used
🧠 Learnings (5)
src/main/java/com/wipro/fhir/controller/v3/abha/LoginAbhaV3Controller.java (1)
Learnt from: helenKaryamsetty
PR: PSMRI/FHIR-API#52
File: src/main/java/com/wipro/fhir/controller/v3/abha/LoginAbhaV3Controller.java:18-20
Timestamp: 2024-12-09T16:09:31.513Z
Learning: In the Java Spring Boot project, all controllers, including `LoginAbhaV3Controller.java` at `src/main/java/com/wipro/fhir/controller/v3/abha/`, use the `@CrossOrigin` annotation without parameters to maintain consistency across the codebase.
src/main/java/com/wipro/fhir/controller/facility/FacilityController.java (1)
Learnt from: helenKaryamsetty
PR: PSMRI/FHIR-API#52
File: src/main/java/com/wipro/fhir/controller/v3/abha/LoginAbhaV3Controller.java:18-20
Timestamp: 2024-12-09T16:09:31.513Z
Learning: In the Java Spring Boot project, all controllers, including `LoginAbhaV3Controller.java` at `src/main/java/com/wipro/fhir/controller/v3/abha/`, use the `@CrossOrigin` annotation without parameters to maintain consistency across the codebase.
src/main/java/com/wipro/fhir/controller/patientdatahandler/PatientDataGatewayController.java (1)
Learnt from: helenKaryamsetty
PR: PSMRI/FHIR-API#52
File: src/main/java/com/wipro/fhir/controller/v3/abha/LoginAbhaV3Controller.java:18-20
Timestamp: 2024-12-09T16:09:31.513Z
Learning: In the Java Spring Boot project, all controllers, including `LoginAbhaV3Controller.java` at `src/main/java/com/wipro/fhir/controller/v3/abha/`, use the `@CrossOrigin` annotation without parameters to maintain consistency across the codebase.
src/main/java/com/wipro/fhir/controller/v3/abha/CreateAbhaV3Controller.java (1)
Learnt from: helenKaryamsetty
PR: PSMRI/FHIR-API#52
File: src/main/java/com/wipro/fhir/controller/v3/abha/LoginAbhaV3Controller.java:18-20
Timestamp: 2024-12-09T16:09:31.513Z
Learning: In the Java Spring Boot project, all controllers, including `LoginAbhaV3Controller.java` at `src/main/java/com/wipro/fhir/controller/v3/abha/`, use the `@CrossOrigin` annotation without parameters to maintain consistency across the codebase.
src/main/java/com/wipro/fhir/controller/healthCard/GenerateHealthIDCardController.java (1)
Learnt from: helenKaryamsetty
PR: PSMRI/FHIR-API#52
File: src/main/java/com/wipro/fhir/controller/v3/abha/LoginAbhaV3Controller.java:18-20
Timestamp: 2024-12-09T16:09:31.513Z
Learning: In the Java Spring Boot project, all controllers, including `LoginAbhaV3Controller.java` at `src/main/java/com/wipro/fhir/controller/v3/abha/`, use the `@CrossOrigin` annotation without parameters to maintain consistency across the codebase.
🧬 Code Graph Analysis (1)
src/main/java/com/wipro/fhir/config/CorsConfig.java (1)
src/main/java/com/wipro/fhir/utils/FilterConfig.java (1)
Configuration(9-27)
⏰ Context from checks skipped due to timeout of 90000ms (1)
- GitHub Check: Analyze (java)
🔇 Additional comments (25)
src/main/environment/common_ci.properties (1)
118-118: Addcors.allowed-originsplaceholder for CI environment.
This introduces the central CORS origins configuration; ensure that theCORS_ALLOWED_ORIGINSenvironment variable is defined in your CI settings and that its value is injected correctly at build time.src/main/environment/common_example.properties (1)
114-115: Define default allowed origins in example config.
The patternhttp://localhost:*may not be recognized by Spring’sallowedOrigins(which expects exact matches). Verify whether yourCorsConfigusesallowedOriginPatternsfor wildcard support or adjust this to an explicit list of ports.src/main/java/com/wipro/fhir/controller/patientdatahandler/HigherHealthFacilityController.java (2)
37-37: Removed class-level@CrossOriginannotation.
Ensure that the global CORS configuration (viaCorsConfig/DynamicCorsFilter) covers the/higher/health/facilitybase path for all HTTP methods and handles preflight requests.
67-67: Removed method-level@CrossOriginannotation.
Confirm that the dynamic CORS filter correctly applies to the/get/clinical/dataendpoint, including OPTIONS preflight handling and header allowances.src/main/java/com/wipro/fhir/controller/healthID/CreateHealthIdRecord.java (3)
19-19: Removed class-level@CrossOriginannotation.
Verify that the centralized CORS policy applies to the/healthIDRecordcontroller and that no endpoints are inadvertently blocked.
35-35: Removed method-level@CrossOriginannotation onmapHealthIDToBeneficiary.
Ensure the global filter covers/healthIDRecord/mapHealthIDToBeneficiary, including CORS preflight and header propagation.
57-57: Removed method-level@CrossOriginannotation onaddHealthIdRecord.
Confirm that/healthIDRecord/addHealthIdRecordis included in your centralized CORS configuration, handling both actual requests and preflight checks.src/main/java/com/wipro/fhir/controller/healthIDvalidate/HealthIDValidateController.java (1)
41-94:Details
✅ Verification successful
Verify centralized CORS configuration is working properly.
The systematic removal of
@CrossOriginannotations from the class and methods is well-executed as part of centralizing CORS management. Ensure that the new centralized CORS configuration properly handles cross-origin requests for all endpoints in this controller.
🏁 Script executed:
#!/bin/bash # Description: Verify that centralized CORS configuration exists and is properly configured # Check for CorsConfig class fd -t f "CorsConfig.java" | head -5 # Check for CORS configuration properties fd -t f -e properties | xargs grep -l "cors.allowed-origins" 2>/dev/null # Check for DynamicCorsFilter fd -t f "DynamicCorsFilter.java" | head -5Length of output: 338
🏁 Script executed:
#!/bin/bash # Display the central CORS configuration to verify global mappings echo "+++ CorsConfig.java +++" sed -n '1,200p' src/main/java/com/wipro/fhir/config/CorsConfig.java echo "" echo "+++ DynamicCorsFilter.java +++" sed -n '1,200p' src/main/java/com/wipro/fhir/utils/DynamicCorsFilter.javaLength of output: 2450
Centralized CORS configuration covers all controller endpoints
Your global CORS setup in CorsConfig (registry.addMapping("/**")…) and the DynamicCorsFilter both apply to every endpoint—including those in HealthIDValidateController—so you can safely remove all method-level @crossorigin annotations.
No further changes are needed.src/main/java/com/wipro/fhir/controller/carecontext/CareContextController.java (1)
41-113: LGTM! Systematic CORS annotation removal.The removal of
@CrossOriginannotations from class and method levels is consistent with the centralized CORS configuration approach. The controller logic remains intact.src/main/java/com/wipro/fhir/controller/healthID/CreateHealthIDWithMobileOTP.java (1)
43-169: LGTM! Complete CORS annotation removal.All
@CrossOriginannotations have been systematically removed from the class and all endpoint methods. The controller functionality remains unchanged, and this aligns with the centralized CORS configuration approach.src/main/java/com/wipro/fhir/controller/generateresource/ResourceRequestGateway.java (1)
52-147:Details
✅ Verification successful
Excellent! Complete CORS refactoring.
The systematic removal of all
@CrossOriginannotations from class and method levels is well-executed. This completes the centralization of CORS configuration for this controller.
🏁 Script executed:
#!/bin/bash # Description: Verify that CORS refactoring is complete across the entire codebase # Check for any remaining @CrossOrigin annotations in controllers rg -A 2 -B 2 "@CrossOrigin" --type java src/ # Verify centralized CORS configuration files exist echo "=== Checking for CorsConfig class ===" fd "CorsConfig.java" src/ | xargs cat 2>/dev/null || echo "CorsConfig.java not found" echo "=== Checking for DynamicCorsFilter class ===" fd "DynamicCorsFilter.java" src/ | xargs cat 2>/dev/null || echo "DynamicCorsFilter.java not found" echo "=== Checking CORS properties ===" fd -e properties src/ | xargs grep "cors" 2>/dev/null || echo "No CORS properties found"Length of output: 2979
🏁 Script executed:
#!/bin/bash # Verify that the required CORS property definitions are present echo "=== Searching for 'cors.allowed-origins' across the repository ===" rg -n "cors.allowed-origins" . echo "=== Searching for any 'cors' entries in .properties/.yml/.yaml files ===" rg -n "cors" --glob "*.properties" --glob "*.yml" --glob "*.yaml" .Length of output: 1200
CORS Refactoring Complete: Centralized Configuration Verified
- No
@CrossOriginannotations remain in any controller.CorsConfig.javaandDynamicCorsFilter.javaare present and correctly configured.- The
cors.allowed-originsproperty is defined incommon_example.propertiesandcommon_ci.properties.src/main/java/com/wipro/fhir/controller/v3/abha/LoginAbhaV3Controller.java (1)
18-18: Verify central CORS configuration applies correctly to this controllerPer-controller
@CrossOriginannotations were removed in favor of a global CORS setup (CorsConfigandDynamicCorsFilter), which is appropriate. Please ensure that requests to/abhaLoginendpoints (including preflight OPTIONS) correctly include the configured CORS headers. Add integration tests or use tooling (e.g.,curlor browser devtools) to confirm the allowed origins and methods are applied as expected.Also applies to: 28-28, 48-48
src/main/java/com/wipro/fhir/controller/healthID/CreateHealthIDWithBio.java (1)
20-20: Validate global CORS handling for bio-based health ID endpointsThe removal of method-level
@CrossOriginannotations is intentional to centralize CORS. Ensure that the/healthIDWithBioendpoints (verifyBio,generateMobileOTP,confirmWithAadhaarBio) are still reachable from the configured origins and properly support preflight OPTIONS requests under the newDynamicCorsFilterandCorsConfig.Also applies to: 53-53, 75-75
src/main/java/com/wipro/fhir/controller/facility/FacilityController.java (1)
23-23: Confirm removal of @crossorigin is covered by global CORS configController- and method-level
@CrossOriginannotations were removed. Please verify that the global CORS settings (inCorsConfig) correctly apply to/facilityendpoints (getAbdmRegisteredFacilitiesandsaveAbdmFacilityId), including allowing the necessary HTTP methods and handling OPTIONS preflight.Also applies to: 34-34, 57-57
src/main/java/com/wipro/fhir/controller/eaushdhi/EAushadhiController.java (1)
50-50: Ensure central CORS filter manages all eAushadhi endpointsAll
@CrossOriginannotations were stripped to enforce centralized settings. Double-check thatDynamicCorsFilter(andCorsConfig) correctly set the necessary headers for the/eAushadhiendpoints (getStoreStockDetails,syncDrugDispenseDetails,getFacilityStockProcessLog,updatePatientIssueSyncStatus), including preflight responses.Also applies to: 59-59, 93-93, 116-116
src/main/java/com/wipro/fhir/controller/healthID/CreateHealthIDWithUID.java (1)
41-41: Validate global CORS coverage for UID-based health ID APIMethod- and class-level
@CrossOriginannotations were removed for/healthIDWithUID. Confirm that the centralized CORS setup covers all operations (generateOTP,verifyOTP,checkAndGenerateMobileOTP,verifyMobileOTP,createHealthIDWithUID) and that OPTIONS preflight requests succeed for allowed origins.Also applies to: 73-73, 96-96, 120-120, 144-144
src/main/java/com/wipro/fhir/config/CorsConfig.java (1)
11-12:Details
❓ Verification inconclusive
Verify CORS allowed origins property configuration.
The configuration reads from
cors.allowed-originsproperty. Ensure this property is properly configured in all environments to prevent security vulnerabilities.
🏁 Script executed:
#!/bin/bash # Description: Verify that cors.allowed-origins property is defined in configuration files # Expected: Property should be found in environment configuration files echo "Searching for cors.allowed-origins property definition..." fd -e properties . --exec grep -l "cors.allowed-origins" {} echo -e "\nShowing property values:" fd -e properties . --exec grep "cors.allowed-origins" {}Length of output: 487
Confirm CORS allowed-origins property definitions across all environments
The
cors.allowed-originsproperty is currently defined in:
src/main/environment/common_example.properties→cors.allowed-origins=@CORS_ALLOWED_ORIGINS@src/main/environment/common_ci.properties→cors.allowed-origins=http://localhost:*Please ensure:
- The
@CORS_ALLOWED_ORIGINS@placeholder is replaced with a restricted, explicit list of origins in each deployment environment (dev, staging, prod).- No environment relies on overly broad patterns (e.g., wildcards) that could inadvertently expose the API.
- Environment-specific property files or variables properly override the example/CI defaults.
src/main/java/com/wipro/fhir/controller/v3/abha/CreateAbhaV3Controller.java (1)
18-89: Verify that global CORS configuration covers all endpoints.The removal of
@CrossOriginannotations from this controller is part of centralizing CORS configuration. Ensure that the new global CORS configuration inCorsConfig.javaprovides the same level of access for all endpoints that previously had individual annotations.Based on the retrieved learning, this change breaks the previous consistency of using
@CrossOriginannotations across controllers, but this is intentional as part of the centralization effort.src/main/java/com/wipro/fhir/utils/FilterConfig.java (2)
12-13: LGTM: Proper injection of CORS configuration.The addition of
@Valueannotation to inject thecors.allowed-originsproperty is correctly implemented.
20-21:Details
✅ Verification successful
Verify JwtUserIdValidationFilter constructor supports allowedOrigins parameter.
The filter instantiation now passes
allowedOriginsto the constructor. Ensure thatJwtUserIdValidationFilterhas been updated to accept this parameter and handle CORS appropriately.
🏁 Script executed:
#!/bin/bash # Description: Verify JwtUserIdValidationFilter constructor accepts allowedOrigins parameter # Expected: Constructor should accept (JwtAuthenticationUtil, String) parameters echo "Searching for JwtUserIdValidationFilter constructor..." ast-grep --pattern 'class JwtUserIdValidationFilter { $$$ public JwtUserIdValidationFilter($_, $_) { $$$ } $$$ }'Length of output: 246
🏁 Script executed:
#!/bin/bash echo "Locating JwtUserIdValidationFilter file..." fd JwtUserIdValidationFilter.java echo "Searching for constructor declarations in JwtUserIdValidationFilter..." rg -n "public class JwtUserIdValidationFilter" . rg -n "JwtUserIdValidationFilter(" .Length of output: 670
🏁 Script executed:
#!/bin/bash echo "Listing constructors in JwtUserIdValidationFilter..." rg -n "public JwtUserIdValidationFilter" src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java || true echo "Checking for allowedOrigins usage in constructors or fields..." rg -n "allowedOrigins" src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java || trueLength of output: 839
Confirmed: JwtUserIdValidationFilter supports allowedOrigins parameter
The constructor in src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java now declares
public JwtUserIdValidationFilter( JwtAuthenticationUtil jwtAuthenticationUtil, @Value("${cors.allowed-origins}") String allowedOrigins ) { … }and assigns
allowedOriginsto the corresponding field. The filter’s CORS logic (lines 126–131) correctly checks and splits this value. No further changes required.src/main/java/com/wipro/fhir/controller/healthCard/GenerateHealthIDCardController.java (1)
41-71: LGTM: Consistent with CORS centralization effort.The removal of
@CrossOriginannotations from class and method levels is consistent with the centralized CORS configuration approach implemented inCorsConfig.java. The controller functionality remains unchanged.src/main/java/com/wipro/fhir/controller/patientdatahandler/PatientDataGatewayController.java (1)
44-75: LGTM: @crossorigin annotations successfully removed for centralized CORS configuration.The removal of
@CrossOriginannotations from this controller aligns with the PR objective to centralize CORS handling through the newDynamicCorsFilterand enhancedJwtUserIdValidationFilter. This approach provides better maintainability and consistent CORS policy across the application.src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java (3)
29-33: LGTM: Constructor properly enhanced for CORS support.The constructor correctly accepts the
allowedOriginsconfiguration parameter and stores it for use in CORS validation.
46-58: LGTM: Proper CORS header handling and OPTIONS support.The CORS header implementation correctly:
- Validates origins using the
isOriginAllowedmethod- Sets comprehensive CORS headers including credentials support
- Handles OPTIONS preflight requests appropriately
- Logs the OPTIONS request handling for debugging
125-133: LGTM: Robust origin validation with wildcard support.The
isOriginAllowedmethod properly:
- Handles null/empty checks
- Supports comma-separated origins
- Implements wildcard pattern matching with proper regex escaping
- Includes appropriate logging for debugging
| registry.addMapping("/**") | ||
| .allowedOriginPatterns(allowedOrigins.split(",")) | ||
| .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") | ||
| .allowedHeaders("*") | ||
| .exposedHeaders("Authorization", "Jwttoken") // Explicitly expose headers if needed | ||
| .allowCredentials(true) | ||
| .maxAge(3600) | ||
| ; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Address security concerns in CORS configuration.
The current CORS configuration has several security concerns:
- String splitting without trimming:
allowedOrigins.split(",")doesn't handle whitespace, which could lead to unexpected behavior. - Overly permissive headers: Using
allowedHeaders("*")allows all headers, which might be too broad. - Credentials with patterns: Using
allowCredentials(true)withallowedOriginPatternscan be risky if the patterns are too broad.
Apply this diff to improve security:
- registry.addMapping("/**")
- .allowedOriginPatterns(allowedOrigins.split(","))
- .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
- .allowedHeaders("*")
- .exposedHeaders("Authorization", "Jwttoken") // Explicitly expose headers if needed
- .allowCredentials(true)
- .maxAge(3600)
- ;
+ String[] origins = allowedOrigins.split(",");
+ for (int i = 0; i < origins.length; i++) {
+ origins[i] = origins[i].trim();
+ }
+
+ registry.addMapping("/**")
+ .allowedOriginPatterns(origins)
+ .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
+ .allowedHeaders("Content-Type", "Authorization", "X-Requested-With", "Accept", "Origin")
+ .exposedHeaders("Authorization", "Jwttoken")
+ .allowCredentials(true)
+ .maxAge(3600);📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| registry.addMapping("/**") | |
| .allowedOriginPatterns(allowedOrigins.split(",")) | |
| .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") | |
| .allowedHeaders("*") | |
| .exposedHeaders("Authorization", "Jwttoken") // Explicitly expose headers if needed | |
| .allowCredentials(true) | |
| .maxAge(3600) | |
| ; | |
| String[] origins = allowedOrigins.split(","); | |
| for (int i = 0; i < origins.length; i++) { | |
| origins[i] = origins[i].trim(); | |
| } | |
| registry.addMapping("/**") | |
| .allowedOriginPatterns(origins) | |
| .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") | |
| .allowedHeaders("Content-Type", "Authorization", "X-Requested-With", "Accept", "Origin") | |
| .exposedHeaders("Authorization", "Jwttoken") | |
| .allowCredentials(true) | |
| .maxAge(3600); |
🤖 Prompt for AI Agents
In src/main/java/com/wipro/fhir/config/CorsConfig.java around lines 16 to 23,
improve CORS security by trimming whitespace from each origin after splitting
allowedOrigins by commas, replacing allowedHeaders("*") with a specific list of
allowed headers instead of all headers, and ensure that allowCredentials(true)
is only used if allowedOriginPatterns are strictly defined and not overly broad
to prevent security risks.
| String origin = request.getHeader("Origin"); | ||
| if (origin != null && Arrays.asList(allowedOrigins).contains(origin)) { | ||
| response.setHeader("Access-Control-Allow-Origin", origin); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Improve origin validation with wildcard support and null safety.
The current exact string matching doesn't support wildcard patterns and lacks null safety checks.
-String origin = request.getHeader("Origin");
-if (origin != null && Arrays.asList(allowedOrigins).contains(origin)) {
- response.setHeader("Access-Control-Allow-Origin", origin);
-}
+String origin = request.getHeader("Origin");
+if (origin != null && isOriginAllowed(origin)) {
+ response.setHeader("Access-Control-Allow-Origin", origin);
+}Add the helper method:
private boolean isOriginAllowed(String origin) {
if (origin == null || allowedOrigins == null || allowedOrigins.trim().isEmpty()) {
return false;
}
return Arrays.stream(allowedOrigins.split(","))
.map(String::trim)
.anyMatch(pattern -> origin.matches(pattern.replace(".", "\\.").replace("*", ".*")));
}🤖 Prompt for AI Agents
In src/main/java/com/wipro/fhir/utils/DynamicCorsFilter.java around lines 26 to
29, the origin validation currently uses exact string matching without null
safety or wildcard support. To fix this, add a helper method isOriginAllowed
that checks if the origin is null or empty and then matches it against
allowedOrigins patterns supporting wildcards by converting them to regex.
Replace the existing origin check with a call to this method to improve
validation robustness and flexibility.
| @Value("${cors.allowed-origins}") | ||
| private String[] allowedOrigins; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Configuration type inconsistency with JwtUserIdValidationFilter.
The allowedOrigins is declared as String[] here, but in JwtUserIdValidationFilter it's declared as String. This inconsistency could lead to configuration binding issues.
Ensure consistent configuration property types across all filters:
-@Value("${cors.allowed-origins}")
-private String[] allowedOrigins;
+@Value("${cors.allowed-origins}")
+private String allowedOrigins;Then update the origin checking logic to split the string:
-if (origin != null && Arrays.asList(allowedOrigins).contains(origin)) {
+if (origin != null && isOriginAllowed(origin)) {Add the isOriginAllowed method similar to JwtUserIdValidationFilter.
Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In src/main/java/com/wipro/fhir/utils/DynamicCorsFilter.java around lines 17 to
18, the allowedOrigins field is declared as String[], but in
JwtUserIdValidationFilter it is a single String, causing configuration binding
inconsistency. Change allowedOrigins to a single String to match
JwtUserIdValidationFilter, then update the origin checking logic to split this
string into an array or list before use. Also, add an isOriginAllowed method
similar to the one in JwtUserIdValidationFilter to handle origin validation
consistently.
| if ("OPTIONS".equalsIgnoreCase(request.getMethod())) { | ||
| response.setStatus(HttpServletResponse.SC_OK); | ||
| } else { | ||
| filterChain.doFilter(request, response); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
OPTIONS preflight requests missing CORS headers.
For OPTIONS requests, the filter returns 200 OK but doesn't set the necessary CORS headers that browsers expect for preflight requests.
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
+ String origin = request.getHeader("Origin");
+ if (origin != null && isOriginAllowed(origin)) {
+ response.setHeader("Access-Control-Allow-Origin", origin);
+ response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
+ response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, Accept, Jwttoken");
+ response.setHeader("Access-Control-Allow-Credentials", "true");
+ response.setHeader("Access-Control-Max-Age", "3600");
+ }
response.setStatus(HttpServletResponse.SC_OK);
} else {
filterChain.doFilter(request, response);
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if ("OPTIONS".equalsIgnoreCase(request.getMethod())) { | |
| response.setStatus(HttpServletResponse.SC_OK); | |
| } else { | |
| filterChain.doFilter(request, response); | |
| } | |
| if ("OPTIONS".equalsIgnoreCase(request.getMethod())) { | |
| String origin = request.getHeader("Origin"); | |
| if (origin != null && isOriginAllowed(origin)) { | |
| response.setHeader("Access-Control-Allow-Origin", origin); | |
| response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); | |
| response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, Accept, Jwttoken"); | |
| response.setHeader("Access-Control-Allow-Credentials", "true"); | |
| response.setHeader("Access-Control-Max-Age", "3600"); | |
| } | |
| response.setStatus(HttpServletResponse.SC_OK); | |
| } else { | |
| filterChain.doFilter(request, response); | |
| } |
🤖 Prompt for AI Agents
In src/main/java/com/wipro/fhir/utils/DynamicCorsFilter.java around lines 31 to
35, the code handles OPTIONS requests by setting the status to 200 OK but does
not set the required CORS headers. To fix this, ensure that before setting the
status for OPTIONS requests, you add the necessary CORS headers to the response,
such as Access-Control-Allow-Origin, Access-Control-Allow-Methods, and
Access-Control-Allow-Headers, so that browsers receive the expected headers
during preflight checks.
| @Component | ||
| public class DynamicCorsFilter extends OncePerRequestFilter { | ||
|
|
||
| @Value("${cors.allowed-origins}") | ||
| private String[] allowedOrigins; | ||
|
|
||
| @Override | ||
| protected void doFilterInternal(HttpServletRequest request, | ||
| HttpServletResponse response, | ||
| FilterChain filterChain) | ||
| throws ServletException, IOException { | ||
|
|
||
| String origin = request.getHeader("Origin"); | ||
| if (origin != null && Arrays.asList(allowedOrigins).contains(origin)) { | ||
| response.setHeader("Access-Control-Allow-Origin", origin); | ||
| } | ||
|
|
||
| if ("OPTIONS".equalsIgnoreCase(request.getMethod())) { | ||
| response.setStatus(HttpServletResponse.SC_OK); | ||
| } else { | ||
| filterChain.doFilter(request, response); | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Verification agent
🧩 Analysis chain
Consider potential filter conflict with JwtUserIdValidationFilter.
Both DynamicCorsFilter and JwtUserIdValidationFilter are setting CORS headers, which could lead to conflicts or duplicate headers.
Verify the filter ordering and ensure only one filter handles CORS to avoid conflicts:
🏁 Script executed:
#!/bin/bash
# Check filter registration order and CORS header handling
ast-grep --pattern 'class $_ implements Filter'
ast-grep --pattern 'class $_ extends OncePerRequestFilter'
rg -A 5 "setHeader.*Access-Control"
rg -A 3 "@Component.*Filter"Length of output: 2399
Centralize CORS handling and remove duplicate headers
I’ve identified three places where CORS headers are being set:
src/main/java/com/wipro/fhir/utils/DynamicCorsFilter.javasrc/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.javasrc/main/java/com/wipro/fhir/utils/http/HTTPRequestInterceptor.java
To avoid conflicts or duplicate headers:
• Consolidate all CORS logic into a single filter (e.g. DynamicCorsFilter).
• Remove or disable any response.setHeader("Access-Control-…") calls from JwtUserIdValidationFilter and HTTPRequestInterceptor.
• Ensure your CORS filter runs first by giving it highest precedence. For example:
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class DynamicCorsFilter extends OncePerRequestFilter {
// …
}Or register it explicitly:
@Bean
public FilterRegistrationBean<DynamicCorsFilter> corsFilterRegistration() {
FilterRegistrationBean<DynamicCorsFilter> reg = new FilterRegistrationBean<>(new DynamicCorsFilter());
reg.setOrder(Ordered.HIGHEST_PRECEDENCE);
return reg;
}This will guarantee only one component sets CORS headers and in the correct order.
🤖 Prompt for AI Agents
In src/main/java/com/wipro/fhir/utils/DynamicCorsFilter.java around lines 14 to
37, the CORS headers are set here but also in JwtUserIdValidationFilter and
HTTPRequestInterceptor, causing potential conflicts or duplicate headers. To fix
this, centralize all CORS handling in DynamicCorsFilter by removing or disabling
any response.setHeader("Access-Control-…") calls in JwtUserIdValidationFilter
and HTTPRequestInterceptor. Additionally, ensure DynamicCorsFilter runs first by
adding @Order(Ordered.HIGHEST_PRECEDENCE) annotation or registering it with
FilterRegistrationBean and setting its order to highest precedence.
|
|
||
| private final JwtAuthenticationUtil jwtAuthenticationUtil; | ||
| private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); | ||
| private final String allowedOrigins; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Verification agent
🧩 Analysis chain
Verify configuration property type consistency.
Ensure the cors.allowed-origins property type is consistent with DynamicCorsFilter which expects String[].
Check the configuration property definition and binding:
🏁 Script executed:
#!/bin/bash
# Check property definitions and usage
rg -A 2 -B 2 "cors.allowed-origins"
ast-grep --pattern '@Value("${cors.allowed-origins}") String $_'
ast-groove --pattern '@Value("${cors.allowed-origins}") String[] $_'Length of output: 2549
Unify cors.allowed-origins binding across all filters
We currently inject the same property as both String and String[], which can lead to binding inconsistencies. To align with DynamicCorsFilter (which expects String[]), update the other classes to use String[] as well:
• src/main/java/com/wipro/fhir/utils/FilterConfig.java
• src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java
• src/main/java/com/wipro/fhir/config/CorsConfig.java
Example diff (apply in all three files):
@Value("${cors.allowed-origins}")
- private String allowedOrigins;
+ private String[] allowedOrigins;And in JwtUserIdValidationFilter’s constructor:
- public JwtUserIdValidationFilter(..., @Value("${cors.allowed-origins}") String allowedOrigins) {
+ public JwtUserIdValidationFilter(..., @Value("${cors.allowed-origins}") String[] allowedOrigins) {This ensures Spring binds comma-separated origins correctly everywhere.
🤖 Prompt for AI Agents
In src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java at line 27,
the allowedOrigins field is declared as a String but should be a String array to
match the expected type in DynamicCorsFilter and maintain consistency across
filters. Change the type of allowedOrigins from String to String[] and update
the constructor and any related code to handle a String array. This will ensure
Spring correctly binds the comma-separated origins property uniformly.


📋 Description
JIRA ID:
Please provide a summary of the change and the motivation behind it. Include relevant context and details.
Added cors orign method to restrict from the browsers
✅ Type of Change
ℹ️ Additional Information
Please describe how the changes were tested, and include any relevant screenshots, logs, or other information that provides additional context.
Summary by CodeRabbit